package com.runfast.common.security.spring;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.runfast.common.dao.model.RunfastCuser;
import com.runfast.common.dao.model.RunfastLoginRecord;
import com.runfast.common.dao.model.RunfastLoginRecordExample;
import com.runfast.common.service.RunfastCuserService;
import com.runfast.common.service.RunfastLoginRecordService;
import com.runfast.common.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Date;

/**
 * @author: lijin
 * @date: 2018年06月07日
 */
public class LogoutTokenHandler extends SecurityContextLogoutHandler {
    private RunfastCuserService cuserService;

    private RunfastLoginRecordService loginRecordService;
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        super.logout(request, response, authentication);

        String token = request.getHeader("token");

        if(StringUtils.isBlank(token))throw new BadCredentialsException("token不能为空");

        JWT decode = null;
        try {
            decode = JWT.decode(token);

        }catch (Exception e){
            throw new BadCredentialsException("非法的token");
        }

        Date expiresAt = decode.getExpiresAt();
        if(expiresAt!=null&&expiresAt.before(new Date())){
            throw new BadCredentialsException("token已经过期，请重新登陆");

        }
        Claim claim = decode.getClaim(TokenUtil.USER_ID);
        Integer userId = claim.asInt();

        if(userId!=null){
            RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);
            if(cuser==null)throw  new BadCredentialsException("用户不存在");

            RunfastLoginRecordExample loginRecordExample = new RunfastLoginRecordExample();
            loginRecordExample.or().andAccountTypeEqualTo(0).andAccountIdEqualTo(userId);

            RunfastLoginRecord loginRecordUpdate = new RunfastLoginRecord();
            loginRecordUpdate.setLogoutTime(new Date());
            loginRecordService.updateByExampleSelective(loginRecordUpdate, loginRecordExample);

        }else{
            throw new BadCredentialsException("非法的token");
        }


    }

    public RunfastCuserService getCuserService() {
        return cuserService;
    }

    public void setCuserService(RunfastCuserService cuserService) {
        this.cuserService = cuserService;
    }

    public RunfastLoginRecordService getLoginRecordService() {
        return loginRecordService;
    }

    public void setLoginRecordService(RunfastLoginRecordService loginRecordService) {
        this.loginRecordService = loginRecordService;
    }
}
